package com.cms.jy.utils;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class BasicImageGenerator {

    public static BufferedImage createTextImage(String text, int width, int height) {
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = image.createGraphics();

        // 设置抗锯齿
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        // 背景
        g2d.setColor(Color.BLACK);
        g2d.fillRect(0, 0, width, height);

        // 文字颜色
        g2d.setColor(Color.WHITE);

        // 使用华文楷体，字体大小先设置为一个较大值
        Font font = new Font("平方雨桐体", Font.PLAIN, 512);
        g2d.setFont(font);

        // 将字符串拆分为单个字符
        String[] characters = text.split("");

        // 获取字体度量信息
        FontMetrics fm = g2d.getFontMetrics();
        int charHeight = fm.getHeight();
        int charWidth = fm.charWidth('中'); // 使用一个典型汉字获取宽度

        // 计算整体文本区域尺寸
        int totalHeight = charHeight * characters.length;
        int totalWidth = charWidth;

        // 动态调整字体大小以适应高度
        if (totalHeight > height * 0.8) { // 保持80%的画面空间
            float scaleFactor = (height * 0.8f) / totalHeight;
            font = font.deriveFont(font.getSize() * scaleFactor);
            g2d.setFont(font);
            fm = g2d.getFontMetrics();
            charHeight = fm.getHeight();
            charWidth = fm.charWidth('中');
            totalHeight = charHeight * characters.length;
        }

        // 计算整体垂直居中位置
        int startY = (height - totalHeight) / 2 + fm.getAscent();
        int startX = width / 2;

        // 绘制每个字符（竖直排列）
        for (int i = 0; i < characters.length; i++) {
            String ch = characters[i];
            // 水平居中
            int x = startX - fm.stringWidth(ch) / 2;
            // 垂直排列
            int y = startY + i * charHeight;
            g2d.drawString(ch, x, y);
        }

        g2d.dispose();
        return image;
    }


    public static void saveImage(BufferedImage image, String filename) throws IOException {
        File output = new File(filename);
        ImageIO.write(image, "png", output);
    }

    public static void main(String[] args) throws IOException {
        saveImage(BasicImageGenerator.createTextImage("迷茫", 1080, 1920), "d:/1.png");
    }
}

